package org.example.judge_contest.controller;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.example.judge_common.annotation.AuthAnnotation;
import org.example.judge_common.entity.ResponseResult;
import org.example.judge_common.hander.RetrunMsgException;
import org.example.judge_common.util.IdWorker;
import org.example.judge_common.util.MyUtils;
import org.example.judge_contest.service.ContestProblemService;
import org.example.judge_contest.service.ContestRecordService;
import org.example.judge_contest.service.ContestRegisterService;
import org.example.judge_contest.service.ContestService;
import org.example.judge_feign_api.JudgeClient;
import org.example.judge_pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@Slf4j
@RequestMapping("/contest/problem")
public class ContestProblemController {

    @Autowired
    private IdWorker idWorker;
    @Qualifier("ContestProblemServiceImpl")
    @Autowired
    private ContestProblemService contestProblemService;

    @Qualifier("ContestServiceImpl")
    @Autowired
    private ContestService contestService;

    @Qualifier("ContestRegisterServiceImpl")
    @Autowired
    private ContestRegisterService contestRegisterService;

    @Qualifier("ContestRecordServiceImpl")
    @Autowired
    private ContestRecordService contestRecordService;
    @Autowired
    private JudgeClient judgeClient;
    @PostMapping("/save")
    @AuthAnnotation({Auth.ADMINISTRATOR})
    public ResponseResult save(@RequestBody List<ContestProblem> contestProblem, HttpServletRequest request) throws RetrunMsgException {
//        System.out.println(contestProblem);
//        if(one !=null)return ResponseResult.fail("题目不能重复添加");
        contestProblemService.save(contestProblem);
        return ResponseResult.success();
    }

    @PutMapping("/update")
    @AuthAnnotation({Auth.ADMINISTRATOR})
    public ResponseResult updateById(@RequestBody ContestProblem contestProblem,HttpServletRequest request){
        contestProblemService.updateById(contestProblem);
        return ResponseResult.success();
    }
    @DeleteMapping("/delete/{id}")
    public ResponseResult deleteById(@PathVariable("id") String id){
        contestProblemService.removeById(id);
        return ResponseResult.success();
    }


    /**
     * 获取题目详情
     * @param contestProblemId 题目竞赛关联表ID
     * @return
     */
    @PostMapping("/detail/{id}")
    @AuthAnnotation(Auth.CLIENT)
    public ResponseResult problemDetail(@PathVariable("id") String contestProblemId,HttpServletRequest request){
        ContestProblem byId = contestProblemService.getById(contestProblemId);
        if (byId==null) {
            return ResponseResult.NotData();
        }

        //获取竞赛信息
        Contest contest = contestService.getById(byId.getContestId());
        if(contest.getStatus()==0)return ResponseResult.fail("比赛未开始");
        else if(contest.getStatus()==1){  //比赛进行中，须报名
            //用户
            User loginUser = (User) request.getAttribute("loginUser");
            //获取报名信息,用户须报名
            ContestRegister contestRegister = contestRegisterService.getByUserIdAndContestId(loginUser.getId(), byId.getContestId());
            if(contestRegister==null)return ResponseResult.fail("未报名");
            if(contestRegister.getStatus()!=0)return ResponseResult.fail("用户已被禁赛");
        }
        //获取题目信息
        String problemId = byId.getProblemId();
        Object data = judgeClient.problemDetail(problemId).getData();
        String toJSONString = JSON.toJSONString(data);
        Problem problem = JSON.parseObject(toJSONString, Problem.class);
        problem.setTitle(byId.getContestTitle());

        return ResponseResult.success().setData(problem);
    }

    /**
     * 竞赛中提交答案用户
     * @param submit
     * @param request
     * @return
     */
    @PostMapping("/submit")
    @AuthAnnotation({Auth.CLIENT})
    public ResponseResult ContestSubmit(@RequestBody Submit submit,HttpServletRequest request){
        if(MyUtils.isEmpty(submit.getContestId()))return ResponseResult.fail("不存在的竞赛");
        User loginUser = (User) request.getAttribute("loginUser");
        submit.setIp(request.getLocalAddr());
        submit.setUserId(loginUser.getId());
        //竞赛榜单记录表
        ContestRecord contestRecord = new ContestRecord();
        contestRecord.setCreateTime(new Date());
        //获取竞赛信息
        Contest contest = contestService.getById(submit.getContestId());
//        if(contest.getStatus()==2){  //比赛已结束
//            submit.setContestId(null);
//            //提交代码
//            String submitId = (String) judgeClient.submit(submit).getData();
//            return ResponseResult.success().setData(submitId);
//        } else
        if (contest.getStatus()==0) {  //竞赛未开始
            return ResponseResult.fail("比赛尚未开始");
        } else if (contest.getStatus() == 1) { //竞赛进行中
            //获取报名信息,用户须报名
            ContestRegister contestRegister = contestRegisterService.getByUserIdAndContestId(loginUser.getId(), submit.getContestId());
            if(contestRegister==null)return ResponseResult.fail("未报名");
            if(contestRegister.getStatus()!=0)return ResponseResult.fail("用户已被禁赛");


        }



        submit.setId(idWorker.nextId().toString());

        //加入榜单信息
        if(contest.getStatus()!=0){ //竞赛进行中/已结束

            contestRecord.setContestId(contest.getId());  //比赛id
            contestRecord.setProblemId(submit.getProblemId()); //题目ID
            contestRecord.setUserId(loginUser.getId());      //用户ID
            contestRecord.setSubmitId(submit.getId());       //提交id
            contestRecordService.save(contestRecord);
        }
        //提交代码
        judgeClient.submit(submit).getData();
        return ResponseResult.success().setData(submit.getId());
    }

}
